package com.example.todolist1

import android.R.layout
import android.annotation.SuppressLint
import android.content.ContentValues
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView


class MainActivity : AppCompatActivity() {

    lateinit var helper:DBHelper //延迟初始化
    lateinit var adapter: TodoAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        init() //初始化
    }

    private fun init(){
        helper =DBHelper(this,"todo.db",1)

        adapter=TodoAdapter()

        val recycle=findViewById<RecyclerView>(R.id.recycler)
        recycle.layoutManager=LinearLayoutManager(this)
        recycle.adapter=adapter

        readInDb()

        findViewById<Button>(R.id.btn_save).setOnClickListener {
            saveInput()
        }
//        findViewById<Button>(R.id.btn_delete).setOnClickListener{
//            deleTodo()
//        }

    }

    private fun updateInDb(id: String) {

        val db=helper.writableDatabase
        val rs = db.delete(Todo.TABLE,"id =?", arrayOf(id.toString()))
        saveInput()
        readInDb()

    }

    private fun deleInDb(id: String) {
        val db=helper.writableDatabase

        val rs = db.delete(Todo.TABLE,"id =?", arrayOf(id.toString()))
        Toast.makeText(this,"删除成功" , Toast.LENGTH_LONG).show()

        readInDb()
    }



    private fun saveInput() {
       val text = findViewById<EditText>( R.id.ipt_text).text.toString()

//        writeInSp(text)
//        writeInFile(text)

    saveInDb(text)
}


    private fun saveInDb(text: String) {
        val db = helper.writableDatabase
        val values = ContentValues().apply {
            put(Todo.COL_CONTENT,text)
            put(Todo.COL_TIME,System.currentTimeMillis())
        }
        val rs = db.insert(Todo.TABLE,null,values)

        Toast.makeText(this,if(rs < 0) "保存失败" else "保存成功" , Toast.LENGTH_LONG).show()

        readInDb()

    }

    @SuppressLint("Range")
    private fun readInDb() {
        val db=helper.readableDatabase
        val cursor=db.query(Todo.TABLE,null,null,null,null,null,
            "${Todo.COL_TIME} desc ")
        val arr= arrayListOf<Todo>()
        if(cursor.moveToFirst()){
            do{
                arr.add(
                    Todo(
                        cursor.getString(cursor.getColumnIndex(Todo.COL_CONTENT)),
                        cursor.getLong(cursor.getColumnIndex(Todo.COL_TIME)),
                    ).apply {
                        id = cursor.getInt(cursor.getColumnIndex(Todo.COL_ID))
                    }
                )
            }while (cursor.moveToNext())
        }
        adapter.setData(arr)

        cursor.close()

    }

    inner class TodoAdapter : RecyclerView.Adapter<TodoViewHolder>() {

        val data= arrayListOf<Todo>()
        fun setData(arr:ArrayList<Todo>){
            data.clear()
            data.addAll(arr)
            notifyDataSetChanged()
        }


        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TodoViewHolder {
            val view = LayoutInflater.from(parent.context).inflate(R.layout.item_todo,parent,false)
            //绑定组件
            return TodoViewHolder(view).apply {
                id = view.findViewById(R.id.id)
                content = view.findViewById(R.id.content)
                btnUpdate = view.findViewById(R.id.btn_update)
                btnDelete = view.findViewById(R.id.btn_delete)
            }



        }

        override fun onBindViewHolder(holder: TodoViewHolder, position: Int) {
            holder.render(data[position])

        }

        override fun getItemCount(): Int {
            return data.size
        }

    }


    inner class TodoViewHolder(view: View): RecyclerView.ViewHolder(view){

        var id: TextView?=null
        var content: TextView? = null

        var btnDelete: TextView? = null
        var btnUpdate: TextView? = null

        fun render(todo: Todo) {
            id?.text = todo.id.toString()
            content?.text = todo.content

            btnDelete?.setOnClickListener {
                deleInDb(todo.id.toString())
            }
            btnUpdate?.setOnClickListener {
                val db=helper.writableDatabase
                findViewById<EditText>(R.id.ipt_text).setText(todo.content)
                findViewById<Button>(R.id.btn_save).setOnClickListener {
                    db.delete(Todo.TABLE,"id =?", arrayOf(todo.id.toString()))
                    saveInput()
                }
            }
        }
    }


}

